<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/6
 * Time: 14:12
 */

namespace Common\Model;


class AnalysisModel extends  BaseModel
{
    /**
     * 每日0点统计  用户分布统计-地区分布
     * wwl
     */
    public static function analysisDistribute(){
        $userM = M("u_user_base",null,DB_MAIN_CFG);
        $area = $userM->field("count(*) as areaNum,province,city,district")->group('province,city,district')->order('city ASC,district ASC')->select();
        $sex = $userM->field("count(*) as sexNum,province,city,district,sex")->group('province,city,district,sex')->order('city ASC,district ASC')->select();

        $data = array();
        foreach ($area as $key => $val){
            foreach ($sex as $item){
                if($val['province'] == $item['province'] && $val['city'] == $item['city'] && $val['district'] == $item['district']){
                    if($item['sex'] == UserModel::USER_SEX_MALE){
                        $data[$key]['maleNum'] = $item['sexNum'];
                    } else if($item['sex'] == UserModel::USER_SEX_FEMALE){
                        $data[$key]['femaleNum'] = $item['sexNum'];
                    }
                }
            }
            if(!$data[$key]['maleNum']){
                $data[$key]['maleNum'] = 0;
            } else if(!$data[$key]['femaleNum']){
                $data[$key]['femaleNum'] = 0;
            }
            $data[$key]['totalNum'] = $val['areaNum'];
            $data[$key]['area'] =$val['province'].','.$val['city'].','.$val['district'];
        }
        $M = M();
        $M->execute("TRUNCATE TABLE `statistic_user_distribute`");
        M('statistic_user_distribute',null,DB_MAIN_CFG)->addAll($data);
    }

    /**
     * 用户统计-年龄分布
     * Author：wwl
     */
    public static function analysisAge(){
        $userM = M('u_user_base',null,DB_MAIN_CFG);
        $year = date("Y");
        $age = $userM
                ->field("count(*) as totalNum,year(now())-year(birthday) as realAge")
                ->group("realAge")
                ->order("realAge ASC")
                ->select();

        $sex = $userM
                ->field("count(*) as sexNum,sex,year(now())-year(birthday) as realAge")
                ->group("realAge,sex")
                ->order("realAge ASC")
                ->select();

        $data = array();$ageGroup = array();

        $ageGroup[0]['age'] = '0-0';
        $ageGroup[1]['age'] = '1-19';
        $ageGroup[2]['age'] = '20-24';
        $ageGroup[3]['age'] = '25-29';
        $ageGroup[4]['age'] = '30-34';
        $ageGroup[5]['age'] = '35-99';

        foreach ($age as  $k => $v) {
            foreach ($sex as $item) {
                if ($v['realAge'] == $item['realAge']) {
                    if($item['sex'] == UserModel::USER_SEX_MALE){
                        $data[$k]['maleNum'] = $item['sexNum'];
                    } else if($item['sex'] == UserModel::USER_SEX_FEMALE){
                        $data[$k]['femaleNum'] = $item['sexNum'];
                    }
                }
            }
            if(!$data[$k]['maleNum']){
                $data[$k]['maleNum'] = 0;
            } else if(!$data[$k]['femaleNum']){
                $data[$k]['femaleNum'] = 0;
            }
            $data[$k]['groupNum'] = $v['totalNum'];
            if($v['realAge'] == $year){
                $data[$k]['ageGroup'] = '0-0';
            } else{
                if($v['realAge'] < 20){
                    $data[$k]['ageGroup'] = '1-19';
                } elseif($v['realAge'] < 25){
                    $data[$k]['ageGroup'] = '20-24';
                } elseif($v['realAge'] < 30){
                    $data[$k]['ageGroup'] = '25-29';
                } elseif($v['realAge'] < 35){
                    $data[$k]['ageGroup'] = '30-34';
                } else{
                    $data[$k]['ageGroup'] = '35-99';
                }
            }
        }

        foreach ($ageGroup as $key => $val){
            foreach ($data as $value){
                if($val['age'] == $value['ageGroup']){
                    $ageGroup[$key]['maleNum'] += $value['maleNum'];
                    $ageGroup[$key]['femaleNum'] += $value['femaleNum'];
                    $ageGroup[$key]['groupNum'] += $value['groupNum'];
                }
            }
            if(!$ageGroup[$key]['maleNum'] && !$ageGroup[$key]['femaleNum'] && !$ageGroup[$key]['groupNum']){
                $ageGroup[$key]['maleNum'] = 0;
                $ageGroup[$key]['femaleNum'] = 0;
                $ageGroup[$key]['groupNum'] = 0;
            }
        }
        $M = M();
        $M->execute("TRUNCATE TABLE `statistic_user_age`");
        M('statistic_user_age',null,DB_MAIN_CFG)->addAll($ageGroup);
    }

    /*
     *统计报表
     * @param $beginTime 统计数据开始时间戳
     * @param $endTime 统计数据结束时间戳
     * @param $addTime 统计数据保存时间戳
     * author:wwl
     */
    public static function reportForm($beginTime,$endTime,$addTime){
        $where = "between {$beginTime} and {$endTime}";
        //新增用户
        $addUserNum = M('u_user_base',null,DB_MAIN_CFG)->where("regTime ".$where)->count();
        //新增手机绑定
        $addBindNum = M('statistic_bind_phone',null,DB_MAIN_CFG)
            ->where("addTime ".$where)->getField("bindNumber");
//        $operation = OPT_BIND_PHONE;
//        $addBind = M('u_operation_log',null,DB_MAIN_CFG)
//            ->where("operation = {$operation}")
//            ->group("uid")
//            ->min("addTime");
//        foreach ($addBind as $key => $val){
//            if($val['addTime'] < $beginTime || $val['addTime'] > $endTime){
//                unset($addBind[$key]);
//            }
//        }
//        $addBindNum = count($addBind);
        //新增付费
        $orderM = M('o_order',null,DB_MAIN_CFG);
        $addOrder = $orderM->where("cashFee > 0")->group("uid")->min("payTime");
        foreach ($addOrder as $key => $val){
            if($val['payTime'] < $beginTime || $val['payTime'] > $endTime){
                unset($addOrder[$key]);
            }
        }
        $addOrderNum = count($addOrder);
        //点赞人数
        $praiseNum = M('praise_log',null,DB_MAIN_CFG)->where("addTime ". $where)->count("distinct uid");
        //评论人数
        $M = M();
        $comment = $M->query("SELECT count(DISTINCT uid) as commentNum FROM(
SELECT uid FROM comment_1 WHERE addTime ". $where ." UNION 
SELECT uid FROM comment_2 WHERE addTime ". $where ." UNION 
SELECT uid FROM comment_3 WHERE addTime ". $where ." UNION 
SELECT uid FROM comment_4 WHERE addTime ". $where .") abc");
        //输出的comment为二维数组[0]=>[commentNum]=>16797;
        //发稿人数
        $writeArticleNum = M('article',null,DB_MAIN_CFG)->where("uid > 0 and addTime ".$where)->count("distinct uid");
        //活跃人数
        $activeNum = M('u_login_log',null,DB_MAIN_CFG)->where("addTime ".$where)->count("distinct uid");
        //兑换人数
        $point = $M->query("SELECT count(DISTINCT uid) as exchangeNum FROM (
SELECT uid FROM exchange_log WHERE exchangeTime ". $where ." UNION
SELECT uid FROM point_lottery_join  WHERE addTime ". $where .") abc");
        //付费金额
        $cashNum = $orderM->where("payTime ".$where)->sum("cashFee");
        //付费人数
        $payNum = $orderM->where("payTime ".$where)->count("distinct uid");

        $data = array(
            'addTime'           => $addTime,
            'addUserNum'        => $addUserNum,
            'addBindNum'        => $addBindNum,
            'addOrderNum'       => $addOrderNum,
            'praiseNum'         => $praiseNum,
            'commentNum'        => $comment[0]['commentNum'],
            'writeArticleNum'   => $writeArticleNum,
            'activeNum'         => $activeNum,
            'exchangeNum'       => $point[0]['exchangeNum'],
            'cashNum'           => $cashNum,
            'payNum'            => $payNum,
        );

        return $data;

    }
//日报表
    public static function dayReportForm(){
        //获取昨日起始时间戳和结束时间戳
        $beginYesterday=mktime(0,0,0,date('m'),date('d')-1,date('Y'));  //昨日开始时间戳
        $endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;    //昨日结束时间戳
//        数据对象时间（12点）
        $objTime = STATISTIC_DAILY_OBJTIME;
        $data = self::reportForm($beginYesterday,$endYesterday,$objTime);
        M('statistic_report_daily',null,DB_MAIN_CFG)->add($data);
    }
//周报表
    public static function weekReportForm(){
        //获取上周起始时间戳和结束时间戳
        $beginLastWeek=mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));
        $endLastWeek=mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'));
        //数据对象时间(周三)
        $objTime = STATISTIC_WEEKLY_OBJTIME;

        $data = self::reportForm($beginLastWeek,$endLastWeek,$objTime);
        M('statistic_report_weekly',null,DB_MAIN_CFG)->add($data);
    }
//月报表
    public static function monthReportForm(){
        //获取上月起始时间戳和结束时间戳
        $lastMonTime = UtilsModel::getLastMonth();
        //数据对象时间(15号)
        $objTime = STATISTIC_MONTHLY_OBJTIME;
        $data = self::reportForm($lastMonTime[0],$lastMonTime[1],$objTime);
        M('statistic_report_monthly',null,DB_MAIN_CFG)->add($data);
    }
//日活跃
    public static function dailyActive(){
        $beginYesterday=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
        $endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
        //        数据对象时间（12点）
        $objTime = STATISTIC_DAILY_OBJTIME;
        $where = " between {$beginYesterday} and {$endYesterday}";
        $loginM = M('u_login_log',null,DB_MAIN_CFG);
        //日总活跃用户
        $dailyActiveUser = $loginM->where("addTime ".$where)->distinct(true)->getField("uid",true);
        $allActiveUserNum = count($dailyActiveUser);
        //当日新用户
        $newUser = M('u_user_base',null,DB_MAIN_CFG)->where("regTime ".$where)->distinct(true)->getField("uid",true);
        $newUserNum = count($newUser);
        //七日之内有过登录用户
        $sevenDayBegin = strtotime("-7 days",$beginYesterday);
        $sevenDayEnd = strtotime("-1 days",$endYesterday);
        $activeUser = $loginM->where("addTime between {$sevenDayBegin} and $sevenDayEnd")->distinct(true)->getField("uid",true);
        //老用户
        if($dailyActiveUser) $dailyActiveUserStr = implode(',',$dailyActiveUser);
        else $dailyActiveUserStr = 0;
        if($activeUser) $activeUserStr = implode(',',$activeUser);
        else $activeUserStr = 0;
        if($newUser) $newUserStr = implode(',',$newUser);
        else $newUserStr = 0;
        $loyalUserNum = $loginM->where("uid NOT IN ({$newUserStr}) and uid IN ({$dailyActiveUserStr},{$activeUserStr})")->count("distinct uid");
        //流失回归用户
        $backUserNum = $loginM->where("uid IN ({$dailyActiveUserStr}) and uid NOT IN ({$activeUserStr})")->count("distinct uid");

        $data = array(
            'timeStr'           => $objTime,
            'totalActiveUser'   => $allActiveUserNum,
            'newUser'           => $newUserNum,
            'oldUser'           => $loyalUserNum,
            'lossComeback'      => $backUserNum
        );
        M("stat_active_daily",null,DB_MAIN_CFG)->add($data);
    }
//月活跃
    public static function monthlyActive(){
        //获取上月起始时间戳和结束时间戳
        $lastMonTime = UtilsModel::getLastMonth();
        //数据对象时间(15号)
        $objTime = STATISTIC_MONTHLY_OBJTIME;

        $loginM = M('u_login_log',null,DB_MAIN_CFG);
        //月总活跃用户
        $monthlyActiveUser = $loginM->where("addTime between {$lastMonTime[0]} and {$lastMonTime[1]}")->distinct(true)->getField("uid",true);
        $allActiveUserNum = count($monthlyActiveUser);
        if($monthlyActiveUser) $monthlyActiveUserStr = implode(',',$monthlyActiveUser);
        else $monthlyActiveUserStr = 0;
        //当月新用户
        $newUser = M('u_user_base',null,DB_MAIN_CFG)->where("regTime between {$lastMonTime[0]} and {$lastMonTime[1]}")->distinct(true)->getField("uid",true);
        $newUserNum = count($newUser);
        if($newUser) $newUserStr = implode(',',$newUser);
        else $newUserStr = 0;
        //流失回归用户(12月统计11月数据，10月未登录视为流失,10月未登录11月登录视为流失回归)
        $firstTwoMonth = UtilsModel::getLastMonth(-2);
        $activeUser = $loginM->where("addTime between {$firstTwoMonth[0]} and {$firstTwoMonth[1]}")->distinct(true)->getField("uid",true);
        if($activeUser) $activeUserStr = implode(',',$activeUser);
        else $activeUserStr = 0;
        $lostComeback = $loginM->where("uid NOT IN ({$activeUserStr},{$newUserStr}) and uid IN ({$monthlyActiveUserStr})")->distinct(true)->getField("uid",true);
        $lostComebackNum = count($lostComeback);
        if($lostComeback) $lostComebackStr = implode(',',$lostComeback);
        else $lostComebackStr = 0;
        //老用户
        $loyalUserNum = $loginM->where("uid IN ({$monthlyActiveUserStr}) and uid NOT IN ({$newUserStr},{$lostComebackStr})")->count("distinct uid");

        $data = array(
            'timeStr'           => $objTime,
            'totalActiveUser'   => $allActiveUserNum,
            'newUser'           => $newUserNum,
            'oldUser'           => $loyalUserNum,
            'lossComeback'      => $lostComebackNum
        );
        M("stat_active_monthly",null,DB_MAIN_CFG)->add($data);
    }
//受众类型分析
    //活动类型受众分析
    public static function eventTypeAnalysis(){
        $contentType=getContentTypeKv();
        $data = M('e_events',null,DB_MAIN_CFG)
                ->where("del=0")
                ->field("contentType,count(*) as eventNum,sum(applyCount) as applyNum,AVG(applyCount) as avgApplyNum,sum(hot) as hotNum,AVG(hot) as avgHotNum")
                ->group("contentType")
                ->select();

        foreach ($data as $key => $item){
            $data[$key]['typeID'] = $item['contentType'];
            if(array_key_exists($item['contentType'],$contentType)){
                $data[$key]['typeName'] = $contentType[$item['contentType']];
            } else{
                $data[$key]['typeName'] = "未知";
            }
        }
        $M = M();
        $M->execute("TRUNCATE TABLE `statistic_type_event`");
        M('statistic_type_event',null,DB_MAIN_CFG)->addALL($data);
    }
    //文章类型受众分析
    public static function articleTypeAnalysis(){
        $contentType=getContentTypeKv();
        $list=M("article",null,DB_MAIN_CFG)
                ->where("audit = ".AUDIT_PASS)
                ->group('contentType')
                ->field("contentType,count(1) as articleNum,sum(viewNum) as viewNum,AVG(viewNum) as avgViewNum,sum(commentNum) as commentNum,AVG(commentNum) as avgCommentNum,sum(praiseNum) as praiseNum,AVG(praiseNum) as avgPraiseNum")
                ->select();
        foreach ($list as $key => $item){
            $list[$key]['typeID'] = $item['contentType'];
            if(array_key_exists($item['contentType'],$contentType)){
                $list[$key]['typeName'] = $contentType[$item['contentType']];
            } else{
                $list[$key]['typeName'] = "未知";
            }
        }
        $M = M();
        $M->execute("TRUNCATE TABLE `statistic_type_article`");
        M('statistic_type_article',null,DB_MAIN_CFG)->addALL($list);
    }
    //商品类型受众分析
    public static function GoodsTypeAnalysis(){
        $contentType=getContentTypeKv();
        //积分商城（兑换、秒杀、换购）
        $pointMall = M('point_mall',null,DB_MAIN_CFG)
                    ->where("status=".PointMallModel::POINTMALL_IS_ONLINE)
                    ->field("contentType,count(1) as goodsNum")
                    ->group("contentType")
                    ->select();

        $pointMallLogM = M('exchange_log',null,DB_MAIN_CFG);
        $cashAndPoint = $pointMallLogM
                    ->where('status='.PointMallModel::EXCHANGE_STATUS_SUCCESS)
                    ->field("sum(costPoint) as costPointNum,sum(costCash) as costCashNum,objContentType")
                    ->group("objContentType")
                    ->select();
        $exchange = $pointMallLogM
                    ->where('status='.PointMallModel::EXCHANGE_STATUS_SUCCESS)
                    ->field("objContentType,count(1) as exchangeNum")
                    ->group("pid,uid")
                    ->select();
        $exchangeNum=array();$lotteryNum = array();
        foreach ($contentType as $key => $item){
            $exchangeNum[$key] = 0;
            $lotteryNum[$key] = 0;
        }
        foreach ($exchange as $item){
            foreach ($exchangeNum as $key => $val){
                if($item['objContentType'] == $key){
                    $exchangeNum[$key] += 1;
                }
            }
        }
        //积分抽奖
        $pointLottery = M('point_lottery',null,DB_MAIN_CFG)
                    ->where("status=".PointLotteryModel::POINTLOTTERY_IS_ONLINE)
                    ->field("prizeType,count(*) as goodsNum")
                    ->group("prizeType")
                    ->select();
        $joinM = M('point_lottery_join',null,DB_MAIN_CFG);
        $point = $joinM
                    ->field("sum(costPoint) as costPointNum,prizeType")
                    ->group("prizeType")
                    ->select();
        $lottery = $joinM
                    ->field("prizeType,count(1) as lotteryNum")
                    ->group("lotteryID,uid")
                    ->select();
        foreach ($lottery as $item){
            foreach ($lotteryNum as $key => $val){
                if($item['prizeType'] == $key){
                    $lotteryNum[$key] += 1;
                }
            }
        }

        foreach ($pointMall as $key => $val){
            foreach ($cashAndPoint as $item){
               if($val['contentType'] == $item['objContentType']){
                   $pointMall[$key]['costPointNum'] = $item['costPointNum'];
                   $pointMall[$key]['costCashNum'] = $item['costCashNum'];
               }
            }
            $pointMall[$key]['typeID'] = $val['contentType'];
            if(array_key_exists($val['contentType'],$contentType)){
               $pointMall[$key]['typeName'] = $contentType[$val['contentType']];
            } else{
               $pointMall[$key]['typeName'] = "未知";
            }
            if(!$pointMall[$key]['costPointNum'])   $pointMall[$key]['costPointNum']=0;
            if(!$pointMall[$key]['costCashNum'])   $pointMall[$key]['costCashNum']=0;
           foreach ($exchangeNum as $k => $v){
               if($val['contentType'] == $k){
                   $pointMall[$key]['exchangeNum'] = $v;
               }
           }
        }

        foreach ($pointLottery as $key => $val){
            foreach ($point as $item){
                if($val['prizeType'] == $item['prizeType']){
                    $pointLottery[$key]['costPointNum'] = $item['costPointNum'];
                }
            }
            $pointLottery[$key]['typeID'] = $val['prizeType'];
            if(array_key_exists($val['prizeType'],$contentType)){
                $pointLottery[$key]['typeName'] = $contentType[$val['prizeType']];
            } else{
                $pointLottery[$key]['typeName'] = "未知";
            }
            if(!$pointLottery[$key]['costPointNum'])   $pointLottery[$key]['costPointNum']=0;
            foreach ($lotteryNum as $k => $v){
                if($val['prizeType'] == $k){
                    $pointLottery[$key]['exchangeNum'] = $v;
                }
            }
        }
        $data = array();
        foreach ($pointMall as $key => $val){
            foreach ($pointLottery as $item) {
                if ($val['contentType'] == $item['prizeType']) {
                    $pointMall[$key]['goodsNum'] += $item['goodsNum'];          //商品数量
                    $pointMall[$key]['exchangeNum'] += $item['exchangeNum'];    //兑换人数
                    $pointMall[$key]['costPointNum'] += $item['costPointNum'];  //消费积分
                }
            }
            $data[$key]['typeID'] = $val['typeID'];
            $data[$key]['typeName'] = $val['typeName'];
            $data[$key]['goodsNum'] = $pointMall[$key]['goodsNum'];
            $data[$key]['exchangeNum'] = $pointMall[$key]['exchangeNum'];
            $data[$key]['avgExchangeNum'] = round($pointMall[$key]['exchangeNum']/$pointMall[$key]['goodsNum']);
            $data[$key]['costPointNum'] = $pointMall[$key]['costPointNum'];
            $data[$key]['avgCostPointNum'] = round($pointMall[$key]['costPointNum']/$pointMall[$key]['goodsNum']);
            $data[$key]['costCashNum'] = $val['costCashNum'];
            $data[$key]['avgCostCashNum'] = round($val['costCashNum']/$pointMall[$key]['goodsNum']);
        }
        $M = M();
        $M->execute("TRUNCATE TABLE `statistic_type_goods`");
        M('statistic_type_goods',null,DB_MAIN_CFG)->addALL($data);
    }
    //积分统计
    public static function pointAnalysis(){
        $beginYesterday=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
        $endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
        //        数据对象时间（12点）
        $objTime = STATISTIC_DAILY_OBJTIME;

        $pointM = M('u_point_log',null,DB_MAIN_CFG);
        $where = "addTime between {$beginYesterday} and {$endYesterday}";
        $outPutPoint = $pointM
                    ->where($where)
                    ->field("uid,act,changeVal,addOrReduce")
                    ->select();

        $data = array(
            'addTime'               => $objTime,
            'totalPoint'            => 0,
            'dayOutPutPoint'        => 0,
            'signOutPutPoint'       => 0,
            'commentOutPutPoint'    => 0,
            'praiseOutPutPoint'     => 0,
            'contributeOutPutPoint' => 0,
            'consumeOutPutPoint'    => 0,
            'outPutCount'           => 0,
            'dayConsumePoint'       => 0,
            'fullLotteryConsumePoint'   => 0,
            'fixLotteryConsumePoint'   => 0,
            'pointMallConsumePoint'     => 0,
            'applyEventConsumePoint'    => 0,
            'consumeCount'              => 0,
        );

        foreach ($outPutPoint as $val){
            if($val['act'] == OPT_COMMENT){
                $data['commentOutPutPoint'] +=1;        //评论产出
            } elseif ($val['act'] == OPT_PRAISE){
                $data['praiseOutPutPoint'] +=1;         //点赞产出
            } elseif ($val['act'] == OPT_CONTRIBUTE){
                $data['contributeOutPutPoint'] +=1;     //投稿产出
            } elseif ($val['act'] == OPT_APPLY_EVENT){
                $data['applyEventConsumePoint'] +=1;    //活动报名消耗
            } elseif ($val['act'] == OPT_APPLY_POINTMALL){
                $data['pointMallConsumePoint'] +=1;     //积分商城消耗
            } elseif ($val['act'] == OPT_FULL_LOTTERY){
                $data['fullLotteryConsumePoint'] +=1;   //满员抽奖消耗
            } elseif ($val['act'] == OPT_FIX_LOTTERY){
                $data['fixLotteryConsumePoint'] +=1;   //定时抽奖消耗
            } elseif ($val['act'] == OPT_SIGN_LUCKY){
                $data['signOutPutPoint'] +=1;           //签到产出
            }
            if($val['addOrReduce'] == VAL_ADD){
                $data['dayOutPutPoint'] += $val['changeVal'];   //日产出积分
            } elseif($val['addOrReduce'] == VAL_REDUCE){
                $data['dayConsumePoint'] += $val['changeVal'];   //日消耗
            }

        }
        $data['totalPoint'] = M('u_user_base',null,DB_MAIN_CFG)->getField("sum(point)");
            $count = $pointM->where($where)->group("addOrReduce")->field("count(distinct uid) as userCount,addOrReduce")->select();
        foreach ($count as $value){
            if($value['addOrReduce'] == VAL_ADD){
                $data['outPutCount'] = $value['userCount'];
            } elseif ($value['addOrReduce'] == VAL_REDUCE){
                $data['consumeCount'] = $value['userCount'];
            }
        }

        M('statistic_point_daily',null,DB_MAIN_CFG)->add($data);

    }
    //用户类型
    public static function userType(){
        $userM = M('u_user_base',null,DB_MAIN_CFG);
        $totalCount = $userM->count();
        $AppUserCount = $userM->where("regFrom = ".CLIENT_FROM_APP)->count();
        $weiXinUid = M('u_user_weixin',null,DB_MAIN_CFG)->getField("uid",true);

        $weiXinUidStr = implode(',',$weiXinUid);
        $onlyFirst = M('u_login_log',null,DB_MAIN_CFG)
                ->field("count(1) as loginTimes,uid")
                ->where("uid IN ({$weiXinUidStr})")
                ->group("uid")
                ->select();
        $onlyFirstCount = 0;
        foreach ($onlyFirst as $val){
            if($val['loginTimes'] < 2){
                $onlyFirstCount +=1;
            }
        }
        $bindPhoneCount = $userM->where("bindPhone IS NOT NULL")->count();
        $payCount = M('o_order',null,DB_MAIN_CFG)->where("cashFee > 0")->count("distinct uid");
        //php获取昨日结束时间戳
        $endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
        $sevenDayAgo = strtotime("-8 days",$endYesterday);

        $lostUserCount = $userM->where("lastLoginTime < {$sevenDayAgo}")->count();

        $data = array(
            'addTime'                   => STATISTIC_DAILY_OBJTIME,
            'totalCount'                => $totalCount,
            'AppUserCount'              => $AppUserCount,
            'weiXinUserCount'           => count($weiXinUid),
            'weiXinUserOnlyFirstCount'  => $onlyFirstCount,
            'bindPhoneUserCount'        => $bindPhoneCount,
            'payUserCount'              => $payCount,
            'lostUserCount'             => $lostUserCount,
        );

        M('statistic_user_type',null,DB_MAIN_CFG)->add($data);

    }
    //上线时间分布(一小时统计一次)
    public static function onlineTime(){
        //前一个小时开始结束时间
        $beginTime = strtotime("-1 hour");
        $endTime = time();
        $count = M('u_login_log',null,DB_MAIN_CFG)->where("addTime between {$beginTime} and {$endTime}")->count("distinct uid");

        $data = array(
            'objTime'       => $beginTime,
            'week'          => date("w",$beginTime),
            'timeGroup'     => date('H',$beginTime).":00-".date('H',$endTime).":00",
            'groupNumber'   => $count,
        );

        M('statistic_user_online',null,DB_MAIN_CFG)->add($data);
    }
    //流失用户统计
    public static function lostUserAnalysis(){
        //php获取昨日起始时间戳和结束时间戳
        $beginYesterday=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
        $endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
        //        数据对象时间（12点）
        $objTime = STATISTIC_DAILY_OBJTIME;

        $sevenDayAgoBegin = strtotime("-8 days",$beginYesterday);
        $sevenDayAgoEnd = strtotime("-8 days",$endYesterday);


        $userM = M('u_user_base',null,DB_MAIN_CFG);

        $todaySilentUser = $userM->where("lastLoginTime between {$sevenDayAgoBegin} and {$sevenDayAgoEnd}")->getField("uid",true);
        $todaySilentUserNumber = count($todaySilentUser);

        $allLostUid = $userM->where("lastLoginTime <= {$sevenDayAgoEnd}")->getField("uid",true);
        $allLostNumber = count($allLostUid);

        if($todaySilentUser){
            $silentUidStr= implode(',',$todaySilentUser);
            $consumeUserNumber = M("o_order",null,DB_MAIN_CFG)->where("uid IN ({$silentUidStr}) and cashFee > 0")->count("distinct uid");   //消费用户
            $bindPhoneUserNumber = $userM->where("uid IN ({$silentUidStr}) and bindPhone IS NOT NULL")->count("distinct uid");              //绑定用户
            $pointMall = M('exchange_log',null,DB_MAIN_CFG)->where("uid IN ({$silentUidStr}) and status=".PointMallModel::EXCHANGE_STATUS_SUCCESS)->distinct(true)->getField("uid",true);
            if($pointMall){
                $pointMallNumber = count($pointMall);
                $pointUserStr = implode(',',$pointMall);
                $pointUserNumber = M('point_lottery_join',null,DB_MAIN_CFG)->where("uid IN ({$silentUidStr}) and uid NOT IN ({$pointUserStr})")->count("distinct uid");
                $pointUserNumber += $pointMallNumber;
            } else{
                $pointUserNumber = M('point_lottery_join',null,DB_MAIN_CFG)->where("uid IN ({$silentUidStr})")->count("distinct uid");
            }

        } else{
            $consumeUserNumber = $bindPhoneUserNumber = $pointUserNumber = 0;
        }

        $totalCount = $userM->count();
        if($allLostUid){
            $lostUidStr = implode(',',$allLostUid);
            $allConsumeNumber = M("o_order",null,DB_MAIN_CFG)->where("uid IN ({$lostUidStr}) and cashFee > 0")->count("distinct uid");   //消费用户
            $allBindNumber = $userM->where("uid IN ({$lostUidStr}) and bindPhone IS NOT NULL")->count("distinct uid");              //绑定用户
            $pointMall = M('exchange_log',null,DB_MAIN_CFG)->where("uid IN ({$lostUidStr}) and status=".PointMallModel::EXCHANGE_STATUS_SUCCESS)->distinct(true)->getField("uid",true);
            if($pointMall){
                $allPointMallNumber = count($pointMall);
                $pointUserStr = implode(',',$pointMall);
                $allPointNumber = M('point_lottery_join',null,DB_MAIN_CFG)->where("uid IN ({$lostUidStr}) and uid NOT IN ({$pointUserStr})")->count("distinct uid");
                $allPointNumber +=$allPointMallNumber;
            } else{
                $allPointNumber = M('point_lottery_join',null,DB_MAIN_CFG)->where("uid IN ({$lostUidStr})")->count("distinct uid");
            }
        } else{
            $allConsumeNumber = $allBindNumber = $allPointNumber = 0;
        }

        $data = array(
            'addTime'               => $objTime,
            'todaySilentNumber'     => $todaySilentUserNumber,
            'totalSilentNumber'     => $allLostNumber,
            'consumeNumber'         => $consumeUserNumber,
            'bindPhoneNumber'       => $bindPhoneUserNumber,
            'pointConsumeNumber'    => $pointUserNumber,
            'allUserNumber'         => $totalCount,
            'allConsumeNumber'      => $allConsumeNumber,
            'allBindNumber'         => $allBindNumber,
            'allPointNumber'        => $allPointNumber
        );
        M('statistic_user_lost',null,DB_MAIN_CFG)->add($data);
    }
    //流失用户来源统计
    public static function lostUserFromAnalysis(){
        //php获取昨日起始时间戳和结束时间戳
        $endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
        $sevenDayAgoEnd = strtotime("-8 days",$endYesterday);

        $userM = M('u_user_base',null,DB_MAIN_CFG);
        $data = $userM->group("regFrom")->field("regFrom as clientFrom,count(1) as totalNumber")->select();
        $fromLost = $userM->group("regFrom")->where("lastLoginTime <= $sevenDayAgoEnd")->field("regFrom,count(1) as fromLostNumber")->select();

        foreach ($data as $key => $val){
            foreach ($fromLost as $v){
                if($val['clientFrom'] == $v['regFrom']){
                    $data[$key]['lostNumber'] = $v['fromLostNumber'];
                }
            }
        }
        $M = M();
        $M->execute("TRUNCATE TABLE `statistic_user_from`");
        M('statistic_user_from',null,DB_MAIN_CFG)->addALL($data);

    }

    //留存统计
    public static function remainAnalysis(){
        //php获取昨日起始时间戳和结束时间戳
        $beginYesterday=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
        $endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
        //数据对象时间（12点）
        $objTime = STATISTIC_DAILY_OBJTIME;
        $remainM = M("statistic_user_remain",null,DB_MAIN_CFG);
        $userM = M('u_user_base',null,DB_MAIN_CFG);

        $newUser = $userM->where("regTime between {$beginYesterday} and {$endYesterday}")->getField("uid",true);
        $obj = array(
            'objTime'       => $objTime,
            'newUserCount'  => count($newUser),
        );
        if($newUser){
            $uidStr = implode(',',$newUser);
            $obj['uidStr'] = $uidStr;
        } else{
            //当日无新增用户，之后的留存都为0
            $obj['uidStr'] = NULL;
            $obj['nextDayRemain'] = 0;
            $obj['thirdDayRemain'] = 0;
            $obj['seventhDayRemain'] = 0;
            $obj['fifteenthDayRemain'] = 0;
            $obj['thirtiethDayRemain'] = 0;
        }
        $remainM->add($obj);

        $data = $remainM->where("thirtiethDayRemain IS NULL and uidStr IS NOT NULL")->select();

        foreach ($data as $key => $val){
            $day = ($objTime - $val['objTime'])/(24*60*60);     //间隔天数
            if($val['uidStr']){
                $remain = $userM->where("uid IN ({$val['uidStr']}) and lastLoginTime >= {$beginYesterday}")->count();
                if($day == 1){
                    //次日留存
                    $remainM->where("objTime = {$val['objTime']}")->setField("nextDayRemain",$remain);
                } elseif ($day == 2){
                    //三日留存
                    $remainM->where("objTime = {$val['objTime']}")->setField("thirdDayRemain",$remain);
                } elseif ($day == 6){
                    //七日留存
                    $remainM->where("objTime = {$val['objTime']}")->setField("seventhDayRemain",$remain);
                } elseif ($day == 14){
                    //十五日留存
                    $remainM->where("objTime = {$val['objTime']}")->setField("fifteenthDayRemain",$remain);
                } elseif ($day == 29){
                    //三十日留存
                    $remainM->where("objTime = {$val['objTime']}")->setField("thirtiethDayRemain",$remain);
                }
            }
        }
    }
}

